<?php

class TemplateSystem {
	const DEFAULT_TEMPLATE = 'Default';
	const TEMPLATE_DIR_NAME = 'templates';

	private $m_current_template = null;
	private $m_templates = null;
	
	public function __construct() {
		$this->m_templates = array();
	} 
	
	public function init($dir) {
		try {
			$d = ($dir) ? $dir : self::TEMPLATE_DIR_NAME;
			$this->loadTemplates($d);
		} catch (Exception $e) {
			throw $e;
		}
	}
	
	public function requestTemplate($name) {
		$requested_template_available = false;
		$current_template_name = $name;
		//debug('Requested template = ' . $current_template_name);
		// Now test availbility
		if ($this->isTemplateAvailable($current_template_name)) {
			//debug('Requested template available');
			$requested_template_available = true;
		} else {
			if ($current_template_name != self::DEFAULT_TEMPLATE) {
				if ($this->isTemplateAvailable(self::DEFAULT_TEMPLATE)) {
					//debug('Requested template not loaded, using default');
					$current_template_name = self::DEFAULT_TEMPLATE;
					$requested_template_available = true;
				}
			}
		}
		if (!$requested_template_available) {
			throw new Exception('Hverken den anmodede eller standard skabelonen kunne findes.');
		}
		$this->m_current_template = $this->getTemplate($current_template_name);
		return $this->m_current_template;
	}
	
	public function getTemplates() {
		return $this->m_templates;
	}
		
	private function loadTemplates($dir_path) {
		if (!is_dir($dir_path)) {
			throw new Exception('Skabelon mappen findes ikke.');
		}
		$dir = opendir($dir_path);
		if (!$dir) {
			throw new Exception('Kan ikke åbne skabelon mappen');
		}
		while (($dirname = readdir($dir)) !== false) {
			// Skip parrent and current directory, and directories starting with a '.'
			if ($dirname == '.' || $dirname == '..' || substr($dirname, 0, 1) == '.') { continue; }
			
			$current_path = $dir_path . '/' . $dirname;
			// If current entry is a directory, accept as a template
			if (is_dir($current_path)) {
				$template = new Template($dirname, $current_path);
				$this->m_templates[] = $template;
			}
		}
		//debug('Loaded templates = ' . count($this->m_templates));
	}
	
	private function isTemplateAvailable($name) {
		foreach ($this->m_templates as $t) {
			if ($t->name == $name) {
				return true;
			}
		}
		return false;
	}
	
	private function getTemplate($name) {
		foreach ($this->m_templates as $t) {
			if ($t->name == $name) {
				return $t;
			}
		}
		return null;
	}
}

?>